import React, { Suspense } from "react";
import { RouterProvider } from "react-router-dom";

import GlobalErrorBoundary from "../components/common/GlobalErrorBoundary";

import { routes } from "./config";
import { DynamicRouteProvider } from "./DynamicRouteProvider";

import { router } from "./index";

// 加载中显示的组件
const LoadingFallback = () => (
  <div className="global-loading">
    <div className="loading-spinner"></div>
    <p>应用加载中...</p>
  </div>
);

/**
 * 应用程序路由根组件
 * 集成了路由提供者、全局错误边界
 */
const AppRouter: React.FC = () => {
  const handleError = (error: Error, errorInfo: React.ErrorInfo) => {
    // 这里可以添加错误上报逻辑
    console.error("[Router Error]", error, errorInfo);
  };

  return (
    <GlobalErrorBoundary onError={handleError}>
      <DynamicRouteProvider initialRoutes={routes}>
        <Suspense fallback={<LoadingFallback />}>
          <RouterProvider router={router} />
        </Suspense>
      </DynamicRouteProvider>
    </GlobalErrorBoundary>
  );
};

export default AppRouter;
